import $ from 'jquery';
import React from 'react';
import { Login } from './pages/auth/auth';
import { Alert } from 'antd';

let global = {
    root: undefined,
    authToken: undefined
};

let api = {
    menuDataURL: "/api/menu/get",
    menuQuery: "/api/menu/query",
    menuSave: "/api/menu/save",
    menuDelete: "/api/menu/delete",
    login: "/api/login",
    crawldata: "/api/webPageCatch/list",
    crawldatastart: "/api/webPageCatch/create",
    queryContent:"/api/content/query",
    saveContent:"/api/content/save",
    delContent:"/api/content/delete"
};

let authToken = localStorage.getItem("x-auth-token");
if (authToken) {
    authToken = JSON.parse(authToken);
    global.authToken = authToken;
}

let processSuccessResponse = (response, textState, xhr) => {
    if (response && response.code) {
        let authToken = xhr.getResponseHeader("X-AUTH-TOKEN");
        if (authToken) {
            global.authToken = authToken;
            localStorage.setItem("x-auth-token", JSON.stringify(authToken));
        }
        if (response.code == "401") {
            global.root.setState({ page: <Login /> });
        }
    }
}

let processErrorResponse = (xhr, textStatus, e) => {
    global.root.setState({ page: <Alert message="系统级错误!" type="error" /> });
}

let beforeSend = (xhr) => {
    if (global.authToken) {
        xhr.setRequestHeader("X-AUTH-TOKEN", global.authToken);
    }
}

let ajax = {
    postJson: (url, data, successFunction, errorFunction) => {
        $.ajax({
            url: url,
            contentType: 'application/json',
            beforeSend: beforeSend,
            type: 'post',
            data: JSON.stringify(data),
            success: (response, statusText, xhr) => {
                processSuccessResponse(response, statusText, xhr);
                successFunction(response, statusText, xhr);
            },
            error: (xhr, textStatus, err) => {
                processErrorResponse(xhr, textStatus, err);
                if (errorFunction) {
                    errorFunction(xhr, textStatus, err);
                }
            }
        });
    },
    post: (url, data, successFunction, errorFunction) => {
        $.ajax({
            url: url,
            type: 'post',
            beforeSend: beforeSend,
            data: data,
            success: (response, statusText, xhr) => {
                processSuccessResponse(response, statusText, xhr);
                successFunction(response, statusText, xhr);
            },
            error: (xhr, textStatus, err) => {
                processErrorResponse(xhr, textStatus, err);
                if (errorFunction) {
                    errorFunction(xhr, textStatus, err);
                }
            }
        });
    }
};

export { api, ajax, global }